package com.easyaop.asm.bytecode.asm;

import com.easyaop.asm.bytecode.MethodInfo;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.util.ASMifier;
import org.objectweb.asm.util.TraceMethodVisitor;

import java.util.LinkedList;
import java.util.List;

public class ClassVisitorReadCode extends FilterClassVisitor {

    public List<MethodInfo> methodInfoList = new LinkedList<>();

    public ClassVisitorReadCode(int api, ClassVisitor classVisitor) {
        super(api, classVisitor);
    }

    @Override
    public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) {
        MethodVisitor methodVisitor = super.visitMethod(access, name, descriptor, signature, exceptions);
        if (test(access, name, descriptor, signature, exceptions)) {

            TraceMethodVisitor traceMethodVisitor = new TraceMethodVisitor(methodVisitor, new ASMifier());

            MethodInfo methodInfo = new MethodInfo(access, name, descriptor, signature, exceptions,traceMethodVisitor.p.text);
            methodInfoList.add(methodInfo);
            methodVisitor = traceMethodVisitor;

            methodVisitor = new MethodVisitor(api, methodVisitor) {
                @Override
                public void visitMaxs(int maxStack, int maxLocals) {
                    methodInfo.maxLocal = maxLocals;
                    super.visitMaxs(maxStack, maxLocals);
                }
            };
        }
        return methodVisitor;
    }

}
